 package xyvcard;

 import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

 public class JavaExecutor {

   public static RunResultWithOutput executeClassAndCaptureOutput(String className, String classPath) {
     RunResultWithOutput result = new RunResultWithOutput();

     ByteArrayOutputStream outContent = new ByteArrayOutputStream();
     PrintStream originalOut = System.out;
     PrintStream originalErr = System.err;

     try (URLClassLoader classLoader = new URLClassLoader(new URL[]{new File(classPath).toURI().toURL()}, Thread.currentThread().getContextClassLoader())) {
         Class<?> loadedClass = classLoader.loadClass(className);
         Method mainMethod = loadedClass.getMethod("main", String[].class);

         // 重定向System.out和System.err到ByteArrayOutputStream
         System.setOut(new PrintStream(outContent));
         System.setErr(new PrintStream(outContent));

         String[] arguments = {};
         mainMethod.invoke(null, (Object) arguments);

         result.setSuccess(true);
         result.setOutput(outContent.toString());
         result.setMessage("Java字节码已成功执行.");
     } catch (Exception e) {
         result.setSuccess(false);
         result.setMessage("执行Java字节码时发生错误: " + e.getMessage());
     } finally {
         // 恢复原始的System.out和System.err
         System.setOut(originalOut);
         System.setErr(originalErr);
     }

     return result;
 }


 }
